
#import <Foundation/Foundation.h>
#import "payRequsestHandler.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
/*
 服务器请求操作处理
 */

static NSString *nonce_str;
static NSDictionary *package;

@implementation payRequsestHandler

{

    
}



-(id) init:(NSString *)body Total_fee:(NSString *)total_fee Order_no:(NSString *)order_no{
    
    //================================
    //预付单参数订单设置
    //================================
    srand( (unsigned)time(0) );
    NSString *noncestr  = [NSString stringWithFormat:@"%d", rand()];
    
    nonce_str = noncestr;

    NSMutableDictionary *packageParams = [NSMutableDictionary dictionary];
    
    //nonce_str = noncestr;
    [packageParams setObject: WX_APP_ID             forKey:@"appid"];       //开放平台appid
    [packageParams setObject: MCH_ID             forKey:@"mch_id"];      //商户号
    [packageParams setObject: nonce_str           forKey:@"nonce_str"];   //随机串
    [packageParams setObject: @"APP"             forKey:@"trade_type"];  //支付类型，固定为APP
    [packageParams setObject: body               forKey:@"body"];        //订单描述，展示给用户
    [packageParams setObject: NOTIFY_URL         forKey:@"notify_url"];  //支付结果异步通知
    [packageParams setObject: order_no            forKey:@"out_trade_no"];//商户订单号
    [packageParams setObject: [self getIPAddress]     forKey:@"spbill_create_ip"];//发起支付的机器ip
    [packageParams setObject: total_fee          forKey:@"total_fee"];       //订单金额，单位为分
    
    package = packageParams;
    
    return self;

}



-(NSString *)getNoncestr{
    return nonce_str;
}

//创建签名
-(NSString*) createMd5Sign:(NSMutableDictionary*)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
        
    }
    //添加key字段
    [contentString appendFormat:@"key=%@", WX_PARTNER_ID];
    //得到MD5 sign签名
    NSString *md5Sign =[WXUtil md5:contentString];
    
    //输出Debug Info
    [debugInfo appendFormat:@"MD5签名字符串：\n%@\n\n",contentString];
    
    return md5Sign;
}


//制作待发送的带签名的XML文件
-(NSString *)getXML
{
    NSString *sign;
    NSMutableString *reqPars=[NSMutableString string];
    //生成签名
    sign = [self createMd5Sign:[NSMutableDictionary dictionaryWithDictionary:package]];
    //生成xml的package
    NSArray *keys = [package allKeys];
    [reqPars appendString:@"<xml>\n"];
    for (NSString *categoryId in keys) {
        [reqPars appendFormat:@"<%@>%@</%@>\n", categoryId, [package objectForKey:categoryId],categoryId];
    }
    [reqPars appendFormat:@"<sign>%@</sign>\n</xml>", sign];
    
    return [NSString stringWithString:reqPars];
}


//获取返回的prayPayID
-(NSString *)getPrepayID
{
    NSString *prepayid = nil;
    
    //获取提交支付
    NSString *send = [self getXML];
    
    //输出Debug Info
    [debugInfo appendFormat:@"API链接:%@\n", [NSString stringWithFormat:@"%@",PAY_URL]];
    [debugInfo appendFormat:@"发送的xml:%@\n", send];
    
    //发送请求post xml数据
    NSData *res = [WXUtil httpSend:[NSString stringWithFormat:@"%@",PAY_URL] method:@"POST" data:send];
    
    //输出Debug Info
    [debugInfo appendFormat:@"服务器返回：\n%@\n\n",[[NSString alloc] initWithData:res encoding:NSUTF8StringEncoding]];
    
    XMLHelper *xml  = [[XMLHelper alloc] init];
    
    //开始解析
    [xml startParse:res];
    
    NSMutableDictionary *resParams = [xml getDict];
    
    //判断返回
    NSString *return_code   = [resParams objectForKey:@"return_code"];
    NSString *result_code   = [resParams objectForKey:@"result_code"];
    if ( [return_code isEqualToString:@"SUCCESS"] )
    {
        //生成返回数据的签名
        NSString *sign = [self createMd5Sign:resParams ];
        NSString *send_sign =[resParams objectForKey:@"sign"] ;
        
        //验证签名正确性
        if( [sign isEqualToString:send_sign]){
            if( [result_code isEqualToString:@"SUCCESS"]) {
                //验证业务处理状态
                prepayid = [resParams objectForKey:@"prepay_id"];
                nonce_str =[resParams objectForKey:@"nonce_str"];
                return_code = 0;
                
                [debugInfo appendFormat:@"获取预支付交易标示成功！\n"];
            }
        }else{
            last_errcode = 1;
            [debugInfo appendFormat:@"gen_sign=%@\n   _sign=%@\n",sign,send_sign];
            [debugInfo appendFormat:@"服务器返回签名验证错误！！！\n"];
        }
    }else{
        last_errcode = 2;
        [debugInfo appendFormat:@"接口返回错误！！！\n"];
    }
    
    return prepayid;
}


-(NSString *)nonce_str{
    return nonce_str;
}

-(long) getLasterrCode
{
    return last_errcode;
}
- (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    //NSLog(@"%@",address);
    return address;
}
@end